//
//  GroupViewController.m
//  Blue-toothLight
//
//  Created by mazg on 15/6/29.
//  Copyright (c) 2015年 mazg. All rights reserved.
//

#import "GroupViewController.h"
#import "OperationBlueTooth.h"
#import "OperationColor.h"
#import "GroupModel.h"

#define WinWidth [UIScreen mainScreen].bounds.size.width
#define WinHeight [UIScreen mainScreen].bounds.size.height

#define W(x) WinWidth*x/320.0
#define H(y) WinHeight*y/568.0

@interface GroupViewController ()<UITextFieldDelegate>{
    OperationColor *colorInstance;
    NSArray *dataBaselightList;
    NSMutableArray *selIndexpathArr;
    BOOL allOpen;
}


@end

@implementation GroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    colorInstance=[OperationColor shareOperationColorInstance];
    dataBaselightList=[LightModel filter:nil orderby:nil offset:0 limit:0];
    selIndexpathArr=[[NSMutableArray alloc]init];
    [self setUpUI];
    [self loadIngTableViewData];
    [self reloadGroupTableViewListData];//刷新分组列表tableview
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    //指定蓝牙模块代理，刷新tableview
//    OperationBlueTooth *tooth=[OperationBlueTooth shareOperationBlueToothInsatnce];
//    tooth.delegate=self;
//    [self reloadGroupTableViewListData];//刷新分组列表tableview
//}

-(void)setUpUI{
    //1、显示搜索列表的tableview
    self.tableView=[[UITableView alloc]init];
    self.tableView.frame=CGRectMake(0, WinHeight, WinWidth, H(350));
    self.tableView.alpha=0.6;
    self.tableView.backgroundColor=[UIColor blackColor];
    [self.view addSubview:self.tableView];
    
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.rowHeight=60;
    
    self.isShowTableView=NO;
    
    //2、设置灯的名字的视图
    self.setView.hidden=YES;
    
    //3、显示所有可以操作的灯的tableView
    self.groupTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.groupTableView.rowHeight=60;
    self.groupTableView.backgroundColor=[UIColor clearColor];
}


-(NSMutableArray *)perForShowArr{
    if (!_perForShowArr) {
        _perForShowArr=[[NSMutableArray alloc]init];
    }
    return _perForShowArr;
}

-(NSMutableArray *)groupTableViewList{
    if (!_groupTableViewList) {
        _groupTableViewList=[[NSMutableArray alloc]init];
    }
    return _groupTableViewList;
}

//刷新分组信息的tableview
-(void)reloadGroupTableViewListData{
    [self.groupTableViewList removeAllObjects];
    NSArray *groupArr=[GroupModel filter:nil orderby:nil offset:0 limit:0];
    for (GroupModel *model in groupArr) {
        [self.groupTableViewList addObject:model];
    }
    [self.groupTableView reloadData];
}

- (IBAction)disMiss:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)addGroup:(id)sender {
    self.isShowTableView=!self.isShowTableView;
    if (self.isShowTableView) {
        [selIndexpathArr removeAllObjects];
        [UIView animateWithDuration:0.5 animations:^{
            self.tableView.frame=CGRectMake(0, WinHeight-H(350), WinWidth, H(350));
        }];
    }
    else{
        [UIView animateWithDuration:0.5 animations:^{
            self.tableView.frame=CGRectMake(0, WinHeight, WinWidth, H(350));
        }];
    }
}

- (IBAction)toggleSwitch:(id)sender {
    
}


- (IBAction)setGroupBtn:(id)sender {
    [self.view endEditing:YES];
    if ([self.setTextfield.text length]==0) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"请设置分组名" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    self.setView.hidden=YES;
    
    //保存分组数据
    GroupModel *model=[GroupModel createNew];
    model.groupName=self.setTextfield.text;
    //这里把所有选择灯泡的UUIDString通过数组保存下来存到数据库
    NSMutableArray *arrM=[[NSMutableArray alloc]init];
    for (NSIndexPath *path in selIndexpathArr) {
        CBPeripheral *per=self.perForShowArr[path.row];
        [arrM addObject:per.identifier.UUIDString];
    }
    NSData *data=[NSKeyedArchiver archivedDataWithRootObject:arrM];
    model.perIdentifierArr=data;
    
    [GroupModel save:^(NSError *error) {
        [self reloadGroupTableViewListData];
    }];
}

- (IBAction)toggleOpen:(id)sender {
    allOpen=!allOpen;
    NSArray *groupArr=[GroupModel filter:nil orderby:nil offset:0 limit:0];
    for (GroupModel *model in groupArr) {
        NSData *data=model.perIdentifierArr;
        NSArray *tmpArr=[NSKeyedUnarchiver unarchiveObjectWithData:data];
        for (NSString *str in tmpArr) {
            for (CBPeripheral *cbp in self.allConnectedPerArr) {
                if ([cbp.identifier.UUIDString isEqualToString:str]) {
                    if (allOpen) {
                        [colorInstance turnOffLightWithPeripheral:cbp];
                    }
                    else{
                        [colorInstance openLightWithPeripheral:cbp];
                    }
                }
            }
        }
    }
}



//第二个tableView(从下方弹出的tableview)
-(void)loadIngTableViewData{
    //1、清空数据，初始化数组
        [self.perForShowArr removeAllObjects];
    
        //2、当前tableview的数据源显示的是 在数据库中存在同时在外围设备数组中也存在的灯
        for (CBPeripheral *per in self.allPerArr) {
            for (LightModel *model in dataBaselightList) {
                if ([model.perIdentifier isEqualToString:per.identifier.UUIDString]) {
                    if (per.state==CBPeripheralStateDisconnected) {
                        [[OperationBlueTooth shareOperationBlueToothInsatnce].cbCentralMgr connectPeripheral:per options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
                    }
                    [self.perForShowArr addObject:per];
                }
            }
        }
        [self.tableView reloadData];
//        [self.groupTableView reloadData];
}


-(LightModel *)getCurrentLightModelWith:(CBPeripheral *)per{
    for (LightModel *model in dataBaselightList) {
        if ([model.perIdentifier isEqualToString:per.identifier.UUIDString]){
            return model;
        }
    }
    return nil;
}

#pragma mark UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        return self.perForShowArr.count;
    }
    else{
        return self.groupTableViewList.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    if ([tableView isEqual:_tableView]) {
        static NSString *identifier=@"cell";
        cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        cell.textLabel.textColor=[UIColor whiteColor];
        CBPeripheral *per=self.perForShowArr[indexPath.row];
        LightModel *model=[self getCurrentLightModelWith:per];
        cell.textLabel.text=model.roomName;
        return cell;
    }
    else{
        cell=[tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.backgroundColor=[UIColor clearColor];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        GroupModel *model=self.groupTableViewList[indexPath.row];
        cell.textLabel.text=model.groupName;
        
        UISwitch *swc=(UISwitch *)[cell viewWithTag:100];
        swc.frame=CGRectMake(W(260), 15, 40, 30);
        swc.on=[self checkAllOpenOrColseWith:model];
        return cell;
    }
    return nil;
}

//检查分组中的灯泡是全部打开，如果全部打开，则返回YES，否则返回NO
-(BOOL)checkAllOpenOrColseWith:(GroupModel *)groupModel{
    NSData *data=groupModel.perIdentifierArr;
    NSArray *tmpArr=[NSKeyedUnarchiver unarchiveObjectWithData:data];
    BOOL isAllOpen=YES;
    for (NSString *str in tmpArr) {
        NSString *pre=[NSString stringWithFormat:@"perIdentifier='%@'",str];
        NSArray *lightModelArr=[LightModel filter:pre orderby:nil offset:0 limit:0];
        LightModel *lightModel=lightModelArr[0];
        BOOL open = [lightModel.isOpen boolValue];
        if (open==NO) {
            isAllOpen=NO;
        }
        else{
            isAllOpen=YES;
        }
    }
    return isAllOpen;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableView]) {
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        if ([selIndexpathArr containsObject:indexPath]) {
            [selIndexpathArr removeObject:indexPath];
            cell.accessoryType=UITableViewCellAccessoryNone;
        }
        else{
            [selIndexpathArr addObject:indexPath];
            cell.accessoryType=UITableViewCellAccessoryCheckmark;
        }
    }
    else{
    
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        UIView *view=[[UIView alloc]init];
        UIImageView *imgView=[[UIImageView alloc]init];
        imgView.frame=CGRectMake(WinWidth/2.0f-25, 0, 50, 30);
        imgView.image=[UIImage imageNamed:@"snsmore.png"];
        [view addSubview:imgView];
        view.userInteractionEnabled=YES;
        UITapGestureRecognizer *gesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addGroup:)];
        [view addGestureRecognizer:gesture];
        
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(WinWidth-80, 0, 60, 30)];
        [btn setTitle:@"完成" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(finishSelectedPer:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:btn];
        
        return view;
    }
    else{
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        return 30;
    }
    else{
        return 0.01;
    }
}


//分组功能，组的灯泡选择完毕
-(void)finishSelectedPer:(UIButton *)sender{
    [self addGroup:nil];
    if (selIndexpathArr.count!=0) {
        self.setView.hidden=NO;
    }
}


#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    textField.text=@"";
    textField.returnKeyType=UIReturnKeyDone;
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self setGroupBtn:nil];
    return YES;
}


#pragma mark HomeViewControllerDelegate
-(void)changeDataWithAllPer:(NSMutableArray *)allPer andConnectedPer:(NSMutableArray *)connectedPer{
    [self.groupTableView reloadData];
}

@end
